﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Host.Models;
using Exception = System.Exception;

namespace Host.Controllers
{
    public class FundController : Controller
    {
        public const int QuestionPageSize = 10;

        private RuleModel _ruleModel = new RuleModel();

        #region View Controllers

        /// <summary>
        /// The view control action 
        /// returns the view for the rules admin page, purpose is to allow configuration of the rules for the system
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = "Administrator, Developer")]
        public ActionResult Rules(RuleModel model, int? page)
        {

            if (model.FundId != 0)
                Session["ruleModel"] = model;

            if (Session["ruleModel"] != null)
                model = (RuleModel)Session["ruleModel"];

            int questionGroupId = model.QuestionGroup;
            int fundId = model.FundId;
            var startPage = 0;
            if (page.HasValue && page.Value > 0)
            {
                startPage = page.Value - 1;
            }
           
            _ruleModel = new RuleModel().GetData(startPage, QuestionPageSize, questionGroupId, fundId);


            return View(_ruleModel);
           
        }



        public ActionResult AdminRule(RuleModel model, int? page)
        {
            if (model.FundId != 0)
                Session["ruleModel"] = model;

            if (Session["ruleModel"] != null)
                model = (RuleModel)Session["ruleModel"];

            int questionGroupId = model.QuestionGroup;
            int fundId = model.FundId;
            var startPage = 0;
            if (page.HasValue && page.Value > 0)
            {
                startPage = page.Value - 1;
            }

            _ruleModel = new RuleModel().GetData(startPage, QuestionPageSize, questionGroupId, fundId);


            return View(_ruleModel);
        }


        [Authorize(Roles = "Administrator, Developer")]
        public ActionResult Fund()
        {
            return View();//returns the view
        }

        public ActionResult CreateRule(Question question )
        {
            return null;
        }

        public ActionResult CreateMap()
        {
            return null;
        }


        public ActionResult GetFunds()
        {
            JsonResult result  = new JsonResult();
            using (Data db = new Data())
            {
                var q = db.Fund.Select(x => x).ToList();
                List<Fund> list = new List<Fund>();
                foreach (var fund in q)
                {
                    list.Add(new Fund
                                 {
                                     FundName = fund.FundName,
                                     EffectiveDate = fund.EffectiveDate.ToShortDateString(),
                                     ValidMonths = fund.ValidMonths.ToString(),
                                     EndDate = fund.EndDate.ToShortDateString()
                                 });
                    result.Data = list;
                }
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult CreateMapForCategory(int CategoryId, string Description)
        {
            try
            {
                MembershipUser user = (MembershipUser)Session["User"];//Get the user from the session object 
                Models.QuestionGroup qg =new Models.QuestionGroup{ QuestionCategoryId = CategoryId, Description = Description};
                qg.DateCreated = DateTime.Now;//Set the created date
                qg.CreatedBy = user.Email;//set the created by property
                new FundRules().CreateMapForCategory(qg);//pass to the model to process
            }
            catch (Exception ex)//catch the exception
            {
                ExceptionHelper.CreateException(0, ex.Message, 99);//Write the exception into the database
            }

            return null;
        }

        /// <summary>
        /// Get the question groups for a certain question category
        /// </summary>
        /// <param name="data">Questioncategory object</param>
        /// <returns>JSON result of QuestionGroup</returns>
        public ActionResult GetQuestionGroupForCategory(int QuestionCategoryId)
        {
            QuestionCategory questionCategory = new QuestionCategory{ QuestionCategoryId = QuestionCategoryId} ;//Get the question category object from the list
            JsonResult result = new JsonResult();//create a new json result object
            result.Data = new FundRules().GetQuestionGroupForCategory(questionCategory);//get the items that need to be returned
            return Json(result, JsonRequestBehavior.AllowGet);//package the result and alow the client to call it.
        }

        
        public ActionResult SaveQuestion(string QuestionDescription, int QuestionCategory, int intQuestionGroup, int AnswerType, bool isGeneral )
        {
           
            MembershipUser user = (MembershipUser)Session["User"];//Get the user from the session object 
            Models.Question question = new Models.Question { QuestionGroupId = intQuestionGroup, Class = "A",
                            Question1 = QuestionDescription, AnswerDataTypeId = AnswerType, DateCreated = DateTime.Now, CreatedBy = user.Email, IsGeneral = isGeneral
            }; 
         //   question.CreatedBy = user.Email;//set the user that created the question
           // question.DateCreated = DateTime.Now;//set the date time for the question when it was created
          new FundRules().SaveQuestion(question);//Send the question to the Model for processing
          //  return Json(result, JsonRequestBehavior.AllowGet);
            return null;
        }

        public ActionResult GetQuestionForQuestionGroup(int QuestionGroupId)
        {
            Models.QuestionGroup qg = new Models.QuestionGroup{ QuestionGroupId = QuestionGroupId};
            JsonResult result = new JsonResult();
            result.Data = new FundRules().GetQuestionForQuestionGroup(qg);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetQuestionMapping(int data, int groupId)
        {
            int funId = data;
            JsonResult result = new JsonResult();
            var list = new Models.Data().FundAnswerSheet.Where(i => i.FundId == funId).Select(x => new MapQuestionAndAnswer
                                                                                                                      {
                                                                                                                          FundAnswerSheetId = x.FundAnswerSheetId,
                                                                                                                          Answer = x.AnswerValue,
                                                                                                                          QuestionId = x.QuestionId
                                                                                                                      });

            List<MapQuestionAndAnswer> newList = new List<MapQuestionAndAnswer>();
            using (Data db = new Data())
            {
                foreach (var mapQuestionAndAnswer in list)
                {
                    Models.Question q = db.Question.Where(i => i.QuestionId == mapQuestionAndAnswer.QuestionId).Select(x => x).Single();
                    if (q.QuestionGroupId == groupId)
                    {
                        mapQuestionAndAnswer.Description = q.Question1;
                        AnswerDataType a =
                            db.AnswerDataType.Where(i => i.AnswerDataTypeId == q.AnswerDataTypeId).Select(x => x).Single();
                        mapQuestionAndAnswer.AnswerType = a.AnswerDataTypeDescription;
                        newList.Add(mapQuestionAndAnswer);
                    }
                }
            }
            result.Data = newList;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SaveFundAnswerSheet(int Fund, int Category, int Group, int Question, string Answer){
            MembershipUser user = (MembershipUser)Session["User"];//Get the user from the session object 
            FundAnswerSheet rec = new FundAnswerSheet{ QuestionId = Question, FundId = Fund, AnswerValue = Answer, DateCreated = DateTime.Now, CreatedBy = user.Email};
            rec.DateCreated = DateTime.Now;
            rec.CreatedBy = user.Email;
            using (Data db = new Data())
            {
                db.FundAnswerSheet.AddObject(rec);
                db.SaveChanges();
            }
            return null;
        }

        public ActionResult DeleteFundAnswerSheet(int FundAnswerSheetId)
        {
            int id = FundAnswerSheetId;
            using (Data db = new Data())
            {
                var del = db.FundAnswerSheet.Where(i => i.FundAnswerSheetId == id).Select(x => x).Single();
                db.FundAnswerSheet.DeleteObject(del);
                db.SaveChanges();
            }
            return null;
        }

        #endregion


    }
    public class Fund
    {
        public string FundName { get; set; }
        public string EffectiveDate { get; set; }
        public string ValidMonths { get; set; }
        public string EndDate { get; set; }

    }

     public class MapQuestions
        {
            public int FundId { get; set; }
            public int QuestionGroupId { get; set; }
        }

       
}
